<template>
  <div class="component-emr-review">
    <EMRCell
      v-for="(item, index) in templates"
      :key="index"
      :docType="docType"
      :title="item.title"
      :subtitle="item.subtitle"
      :data="item.data"
      :ref="setRefs"
      :disabled="disabled"
      :class="{ domScroll1: index === 1 }"
    ></EMRCell>
  </div>
</template>
<script>
  import {
    toRefs,
    reactive,
    watch,
    ref,
    onBeforeMount,
    nextTick,
    provide,
    computed,
  } from 'vue'
  import { cloneDeep, pick, assignIn, flattenDeep } from 'lodash-es'
  import moment from 'moment'
  import { useStore } from 'vuex'
  import { useRoute } from 'vue-router'
  import common from '@/utils/common'
  import { load, save, saveNormalTemplate } from '@/api/modules/emr'
  import { usePromise } from '@/hooks/core/usePromise'
  const { to } = usePromise()
  // eslint-disable-next-line max-len
  import { useAsthmaBus } from '@/views/reception/components/asthma/hooks/useAsthmaBus.ts'
  import { useEmrData } from '@/views/reception/hooks/useEmrData.js'
  export default {
    props: { docType: [String, Number], disabled: Boolean },
    setup(props, context) {
      const store = useStore()
      const route = useRoute()
      const { busDict, addBus, updateBus, deleteBus, busAllEmit } =
        useAsthmaBus()
      function getRecordDateFunc() {
        return props.recordDate
      }
      provide('asthmaBusDict', busDict)
      provide('asthmaBusAddBus', addBus)
      provide('asthmaBusUpdateBus', updateBus)
      provide('asthmaBusDeleteBus', deleteBus)
      provide('busAllEmit', busAllEmit)
      provide('recordDate', getRecordDateFunc)

      let d = reactive({
        refs: [],
        treatmentType: '',
        templates: [],
        originalTemplates: [],
        recordDate: '',
      })

      async function toLoad() {
        common.XmLoading(true)
        const [err, res] = await to(
          load({
            medicalRecordId: +route.query.emrId,
            patientId: props.pid,
            docType: props.docType,
            riskScreeningType: 0,
            recordDate: moment(d.recordDate).format('YYYY-MM-DD HH:mm:ss'),
          })
        )
        common.XmLoading(false)
        if (err) return

        // 更新一下 recordDate
        if (res.data.recordDate)
          d.recordDate = moment(res.data.recordDate).format(
            'YYYY-MM-DD HH:mm:ss'
          )
        d.treatmentType = res.data.treatmentType

        const { filterReview } = useEmrData()
        const reviewsTemplates = filterReview(res.data.caseTempleReq.value)
        d.originalTemplates = cloneDeep(res.data)
        d.templates = reviewsTemplates
      }

      async function saveReview() {
        let data = {
          attrs: [],
          ...pick(d.originalTemplates, [
            'status',
            'files',
            'riskScreeningType',
            'mainSuit',
            'historyPresent',
            'past',
            'personal',
            'signs',
            'imgUrl',
            'family',
            'auxiliaryExamination',
            'diagnosis',
            'followDate',
            'drugOptions',
            'docType',
            'historicalVisitId',
          ]),

          cnDiagnosis: '', // 写死，hunan没有中医模块
          cnDialectical: '', // 写死，hunan没有中医模块

          medicalRecordId: route.query.emrId,

          // 待测试
          ...pick(d.originalTemplates.caseTempleReq, [
            'acuteWheezingActionPlanId',
            'controlActionPlanId',
            'recordDate',
            'treatmentType',
          ]),
        }
        let loopFetchNodeValue = function (nodes) {
          nodes.forEach((item) => {
            if (!item) return
            if (item.an === '520' || item.an == '521') return
            if (item.an && item.b.ip) {
              data.attrs.push({ name: item.an, attrValue: item.b.ip })
            }
            if (item.children) {
              loopFetchNodeValue(item.children)
            }
          })
        }
        let nodes = flattenDeep(
          d.originalTemplates.caseTempleReq.value.map((item) => item.data)
        ).filter((item) => item)

        loopFetchNodeValue(nodes)

        // 填写的复诊数据
        let form = {}
        d.refs.forEach((ref) => {
          let nodeValue = ref.getData()
          assignIn(form, nodeValue)
        })

        let attrs = Object.keys(form).map((attrName) => {
          let value = form[attrName]
          if (attrName === 'attr520')
            value = moment(value).format('YYYY-MM-DD HH:mm:ss')
          return {
            name: attrName,
            attrvalue: value,
          }
        })
        data.attrs = data.attrs.concat(attrs)
        console.log(data)
        return
        // eslint-disable-next-line
        const [err, res] = await to(save(data, false))
        if (err) return
      }

      const setRefs = function (el) {
        console.log('setRefs', el)
        // 这里需要数组长度判断，防止死循环 大于等于后 就不用记录了
        if (el !== null && d.refs.length <= d.templates.length) d.refs.push(el)
      }

      onBeforeMount(async () => {
        toLoad()
      })
      return {
        setRefs,
        ...toRefs(d),
        saveReview,
        toLoad,
      }
    },
  }
</script>
